package com.zhongshengnetwork.rightbe.lang.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.gsonmodel.UserSignModel;
import com.zhongshengnetwork.rightbe.lang.res.Configs;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.util.ArrayList;
import java.util.List;

import static com.zhongshengnetwork.rightbe.MainActivity.REQUEST_PERMISSION;
import static com.zhongshengnetwork.rightbe.MainActivity.REQ_PERM_EXTERNAL_STORAGE;

public class ReadInfoActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private RelativeLayout share_layout;
    private ImageView header;
    private TextView name;

    private int screenWidth = 0;
    private int count = 0;

    private UserSignModel userSignModel = null;

    private Button sign_button;

    private ImageView cover;
    private TextView sign_count;
    private TextView finish_count;
    private TextView distance_count;

    private Button read_button;

    private boolean needGetInfo = false;

    private KyLoadingBuilder load = null;

    private AVLoadingIndicatorView avi;

    private int signtime = 0;

    private void calculateImageWidth(){
        int width = ScreenUtils.getScreenWidth(ReadInfoActivity.this);
        screenWidth = width-ScreenUtils.dip2px(ReadInfoActivity.this, 0);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_info);

        userSignModel =  (UserSignModel) getIntent().getSerializableExtra("model");
        calculateImageWidth();

        avi = (AVLoadingIndicatorView) findViewById(R.id.avi);

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.getRightView().setImageResource(R.drawable.more);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setVisibility(View.VISIBLE);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                more(v);
            }
        });
        topbar.setClickListener(this);

        share_layout = (RelativeLayout) findViewById(R.id.share_layout);

        if (userSignModel == null){
            userSignModel = new UserSignModel();
            userSignModel.setReadCount(0);
            userSignModel.setReadTime(0);
            userSignModel.setTodayTime(0);
            userSignModel.setTip("坚持每天阅读5分钟，让阅读成为你的习惯");
        }

        cover = (ImageView) findViewById(R.id.cover);
        ViewGroup.LayoutParams params = cover.getLayoutParams();
        params.width = screenWidth;
        params.height = Math.round(screenWidth / Configs.Value.COVER_WIDTH_HEIGHT_RATIO);
        cover.setLayoutParams(params);
        if (!CommonUtils.isEmpty(userSignModel.getBgUrl())){
            try{
                Glide.with(ReadInfoActivity.this).load(userSignModel.getBgUrl()).
                        diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
            }catch (Exception e){
                LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
            }
        }else {
            try{
                Glide.with(ReadInfoActivity.this).load(CustomApplication.loginModel.getBackground()).
                        diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(cover);
            }catch (Exception e){
                LangPublishActivity.uploadError("分享页面加载图片报错："+e.getLocalizedMessage());
            }
        }

        header = (ImageView) findViewById(R.id.header);
        Glide.with(ReadInfoActivity.this).load(CustomApplication.loginModel.getHeader()).transform(new CircleTransform(ReadInfoActivity.this)).dontAnimate().into(header);
        name = (TextView) findViewById(R.id.name);
        name.setText(CustomApplication.loginModel.getNickname());

        sign_count = (TextView) findViewById(R.id.sign_count);
        sign_count.setText(""+userSignModel.getReadCount());

        finish_count = (TextView) findViewById(R.id.finish_count);
        finish_count.setText(""+userSignModel.getTodayTime());

        distance_count = (TextView) findViewById(R.id.distance_count);
        distance_count.setText(""+userSignModel.getReadTime());

        read_button = (Button) findViewById(R.id.read_button);
        read_button.setClickable(true);
        read_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userSignModel != null){
                    String content = "";
                    if (userSignModel.getTodayTime() < 5){
                       content = "亲，你今天的阅读时长为"+userSignModel.getTodayTime()+"分钟，尚未完成每天5分钟的阅读任务哦。";
                       content += "\n【坚持每天阅读5分钟，让阅读成为你的习惯】";
                        CustomDialog dialog = null;
                        final CustomDialog.Builder builder = new CustomDialog.Builder(ReadInfoActivity.this);
                        builder.setTitle("温馨提示");
                        builder.setMessage(content);
                        builder.setNegativeButton("我知道了", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        });
                        dialog = builder.create();
                        dialog.show();
                    }else {
                        Intent intent = new Intent(ReadInfoActivity.this, ReadShareActivity.class);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("model", userSignModel);//序列化
                        intent.putExtras(bundle);//发送数据
                        startActivity(intent);
                    }
                }
            }
        });
        updateRead();

    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void more(View view){
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(ReadInfoActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }

        PermissionUtils.isPictureNote(ReadInfoActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag){
                    // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                        if (ContextCompat.checkSelfPermission(ReadInfoActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(ReadInfoActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                    REQUEST_PERMISSION);
                            return;
                        }
                    }else if (ActivityCompat.checkSelfPermission(ReadInfoActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        // 申请权限
                        ActivityCompat.requestPermissions(ReadInfoActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_PERM_EXTERNAL_STORAGE);
                        return;
                    }

                    final List<String> menu = new ArrayList<String>();
                    menu.add("分享");
                    ActionSheetDialog actionSheetDialog = new ActionSheetDialog(ReadInfoActivity.this)
                            .builder()
                            .setTitle("")
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true);
                    for (String m : menu){
                        actionSheetDialog.addSheetItem(m, null, new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (which == 1){
                                    Intent intent = new Intent(ReadInfoActivity.this, ReadShareActivity.class);
                                    Bundle bundle=new Bundle();
                                    bundle.putSerializable("model", userSignModel);//序列化
                                    intent.putExtras(bundle);//发送数据
                                    startActivity(intent);
                                }
                            }
                        });
                    }
                    actionSheetDialog.show();
                }
            }
        });

    }

    private void updateRead(){
        if (userSignModel != null){
            if (userSignModel.getTodayTime() >= 5){
                read_button.setText("已完成");
                read_button.setTextColor(Color.parseColor("#c0c0c0"));
                read_button.setBackgroundResource(R.drawable.signed_bg);
            }else {
                read_button.setText("待完成");
                read_button.setTextColor(Color.parseColor("#99cc00"));
                read_button.setBackgroundResource(R.drawable.unsigned_bg);
            }
        }
    }

}
